<template>
  <div class="banner">
    <h1>预约咨询青书推广</h1>
    <text>留下您的联系方式，我们的营销顾问将为您服务</text>
  </div>
  <div class="center">
    <form action="" @submit.prevent="login()">
      <div class="form-item">
        <label>email :</label>
        <input type="email" placeholder="请输入" v-model="form.email" />
      </div>
      <div class="form-item">
        <label>验 证 码 :</label>
        <div class="verify-code">
          <input type="text" placeholder="请输入" v-model="form.code" />
          <button class="send-code" type="button" @click="sendCode" :disabled="isSendingCode">
            {{ isSendingCode ? `重新发送(${countDown}s)` : '发送验证码' }}
          </button>
        </div>
      </div>
      <button class="login" :disabled="isLogging">登 录</button>
    </form>
  </div>
  <div class="bottom">
    <text>青书官网</text>
    <text>有限公司</text>
  </div>
</template>

<script setup>
import { reactive, ref, onMounted } from 'vue'
import axios from 'axios'
import { useRouter } from 'vue-router'
import { ElNotification } from 'element-plus'
import { useAuthStore } from '@/store/auth'
import { getToken, setToken, setUserInfo, removeToken, removeUserInfo } from '@/utils/auth'

const router = useRouter()
const authStore = useAuthStore()
const dialogVisible = ref(false)
const isSendingCode = ref(false)
const countDown = ref(60)
const isLogging = ref(false)

const form = reactive({
  email: '',
  code: ''
});

// 配置Axios基础路径
onMounted(() => {
  axios.defaults.baseURL = 'http://localhost:8080'

  // 请求拦截器：添加Token
  axios.interceptors.request.use(
    (config) => {
      const token = authStore.token || getToken()
      
      // 排除不需要Token的接口
      const noAuthPaths = [
        '/promot/', 
        /^\/api\/users\/[^\/]+\/[^\/]+$/, // 匹配邮箱验证码登录路径
        /^\/api\/users\/login$/, // 登录路径
        /^\/api\/users\/register$/ // 注册路径
      ];
      
      // 检查URL是否匹配任一排除路径
      const shouldSkipAuth = noAuthPaths.some(path => {
        if (typeof path === 'string') {
          return config.url.includes(path)
        } else if (path instanceof RegExp) {
          return path.test(config.url)
        }
        return false
      })
      
      if (token && !shouldSkipAuth) {
        config.headers.Authorization = `Bearer ${token}`
      }
      return config
    },
    (error) => Promise.reject(error)
  )

  // 响应拦截器：统一处理错误
  axios.interceptors.response.use(
    (response) => response,
    (error) => {
      if (error.response?.status === 401 || error.response?.status === 403) {
        ElNotification({ 
          title: 'Error', 
          message: '登录状态已失效，请重新登录', 
          type: 'error',
          duration: 5000
        })
        authStore.logout()
        router.push('/promotlogin')
      }
      return Promise.reject(error)
    }
  )
})

// 发送验证码
async function sendCode() {
  if (!form.email.trim()) {
    ElNotification({ 
      title: 'Warning', 
      message: '请先输入邮箱！', 
      type: 'warning',
      duration: 3000
    })
    return
  }

  isSendingCode.value = true
  try {
    // 检查并添加Token（如果需要）
    const token = authStore.token || getToken()
    const config = token ? { headers: { Authorization: `Bearer ${token}` } } : {}
    
    const res = await axios.get(`/promot/${form.email}`, config)
    
    if (res.data && res.data.code === 200) {
      ElNotification({ 
        title: 'Success', 
        message: '验证码发送成功，请查看邮箱！', 
        type: 'success',
        duration: 3000
      })
      // 倒计时逻辑
      const timer = setInterval(() => {
        countDown.value--
        if (countDown.value <= 0) {
          clearInterval(timer)
          isSendingCode.value = false
          countDown.value = 60
        }
      }, 1000)
    } else {
      ElNotification({ 
        title: 'Error', 
        message: res.data?.msg || '验证码发送失败', 
        type: 'error',
        duration: 5000
      })
      isSendingCode.value = false
    }
  } catch (e) {
    console.error('验证码发送失败:', e)
    let errorMsg = '验证码发送失败'
    
    if (e.response) {
      if (e.response.data && e.response.data.msg) {
        errorMsg = e.response.data.msg
      } else if (e.response.status === 401) {
        errorMsg = '未授权操作，请先登录'
      }
    }
    
    ElNotification({
      title: 'Error',
      message: errorMsg,
      type: 'error',
      duration: 5000
    })
    isSendingCode.value = false
  }
}

// 登录逻辑
async function login() {
  if (!form.email.trim()) {
    ElNotification({ 
      title: 'Warning', 
      message: '邮箱不能为空', 
      type: 'warning',
      duration: 3000
    })
    return
  }
  if (!form.code.trim()) {
    ElNotification({ 
      title: 'Warning', 
      message: '验证码不能为空', 
      type: 'warning',
      duration: 3000
    })
    return
  }

  isLogging.value = true
  try {
    // 创建不携带Token的请求配置
    const loginConfig = {
      headers: {
        // 明确不添加Authorization头
      }
    }
    
    // 调用后端邮箱验证码登录接口
    const res = await axios.post( `/api/users/login-by-code/${form.email}/${form.code}`, {}, loginConfig)
    
    // 适配后端返回格式
    if (res.data?.code === 200 && res.data?.data) {
      const token = res.data.data
      
      // 创建携带Token的请求配置
      const authConfig = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }
      
      // 使用新Token获取用户信息
      const userRes = await axios.get(`/api/users/by-email?email=${form.email}`, authConfig)
      
      if (userRes.data?.code !== 200 || !userRes.data.data) {
        throw new Error('获取用户信息失败')
      }
      const user = userRes.data.data

      // 更新Pinia全局状态
      authStore.token = token
      authStore.user = user
      authStore.isAuthenticated = true
      
      // 计算Token过期时间
      const expiresIn = 24 * 60 * 60 // 24小时
      const expiryTimestamp = Date.now() + expiresIn * 1000
      authStore.tokenExpiry = expiryTimestamp

      // 存储到本地缓存
      setToken(token)
      setUserInfo(user)
      localStorage.setItem('tokenExpiry', expiryTimestamp)

      // 登录成功：跳转首页
      ElNotification({ 
        title: 'Success', 
        message: '登录成功，即将跳转！', 
        type: 'success',
        duration: 3000
      })
      router.push('/promothome')
    } else {
      // 后端返回的错误信息
      const errorMsg = res.data?.msg || '登录失败'
      ElNotification({ 
        title: 'Error', 
        message: errorMsg, 
        type: 'error',
        duration: 5000
      })
    }
  } catch (error) {
    console.error('登录错误:', error)
    
    // 显示具体错误信息
    let errorMessage = '登录失败，请重试'
    
    if (error.response) {
      // 从响应中获取错误信息
      if (error.response.data && error.response.data.msg) {
        errorMessage = error.response.data.msg
      } else if (error.response.status === 401) {
        errorMessage = '验证码错误或已过期'
      } else if (error.response.status === 404) {
        errorMessage = '用户不存在，请先注册'
      }
    } else if (error.message) {
      errorMessage = error.message
    }
    
    ElNotification({ 
      title: 'Error', 
      message: errorMessage, 
      type: 'error',
      duration: 5000
    })
  } finally {
    isLogging.value = false
  }
}
</script>

<style scoped>
.banner {
  height: 300px;
  display: flex;
  background-color: #4aaff2;
  color: #fff;
  flex-direction: column;
  justify-content: center;
  align-items: flex-start;
  padding: 50px;
}
.banner h1 {
  font-size: 36px;
  margin-bottom: 20px;
}
.banner text {
  font-size: 16px;
  display: block;
}
.center {
  padding: 40px 20px;
  display: flex;
  justify-content: center;
}
.form-item {
  display: flex;
  align-items: center;
  margin-top: 50px;
}
.form-item label {
  width: 100px;
  text-align: right;
  margin-right: 15px;
  font-size: 14px;
  color: #333333;
}
.form-item input {
  flex: 1;
  padding: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
  font-size: 14px;
  transition: border-color 0.2s ease;
}
.form-item input:focus {
  border-color: var(--primary-color);
  outline: none;
}

.verify-code .send-code {
  margin-left: 10px;
  padding: 10px 15px;
  background-color: var(--primary-color);
  border-radius: 4px;
  color: #fff;
  cursor: pointer;
  font-size: 14px;
  transition: background-color 0.2s ease;
  border: none;
}
.verify-code .send-code:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
.verify-code .send-code:hover:not(:disabled) {
  background-color: #66b1ff;
}

.login {
  margin-left: 115px;
  margin-top: 50px;
  padding: 10px 25px;
  background-color: var(--primary-color);
  color: #fff;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
  transition: background-color 0.2s ease;
}
.login:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}
.login:hover:not(:disabled) {
  background-color: #66b1ff;
}

.bottom {
  background-color: #f5f7fa;
  padding: 25px 20px;
  text-align: center;
  color: #666;
  line-height: 1.6;
  font-size: 14px;
}
.bottom text {
  display: block;
  margin: 5px 0;
}
</style>